package com.cb.web.wasf;

import java.io.IOException;
import javax.servlet.ServletException;

/**
 * @author CBO
 */
public interface View {

    void render(Response response) throws UnexpectedViewRenderingException;

    public static class UnexpectedViewRenderingException extends RuntimeException {

        public UnexpectedViewRenderingException(Throwable cause) {
            super(cause);
        }
    }

    public static class JspView implements View {

        private State state;
        private String jspPath;

        public JspView(State state, String jspPath) {
            this.state = state;
            this.jspPath = jspPath;
        }

        public State getState() {
            return state;
        }

        public String getJspPath() {
            return jspPath;
        }

        @Override
        public void render(Response response) {
            try {
                response.getHttpServletRequest().setAttribute("state", getState());
                response.getHttpServletRequest().getRequestDispatcher(jspPath).forward(response.getHttpServletRequest(), response.getHttpServletResponse());
            } catch (IOException ioe) {
                throw new UnexpectedViewRenderingException(ioe);
            } catch (ServletException se) {
                throw new UnexpectedViewRenderingException(se);
            }
        }
    }

    public static class StringView implements View {

        private String value;

        public StringView(String value) {
            this.value = value;
        }

        @Override
        public void render(Response response) throws UnexpectedViewRenderingException {
            try {
                response.getHttpServletResponse().getWriter().print(value);
            } catch (IOException ioe) {
                throw new UnexpectedViewRenderingException(ioe);
            }
        }
    }
}
